import { createRouter, createWebHashHistory } from "vue-router";
import { ElNotification } from "element-plus";
import config from "@/config";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import systemRouter from "./systemRouter";
import addDynamicMenuRoutes from "./dynamicMenuRoute";
import { beforeEach, afterEach } from "./scrollBehavior";
import store from "@/store";

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
// const _import = require("./import-" + process.env.NODE_ENV);
//系统路由
const routes = systemRouter;
//TODO
// flatAsyncRoutes(routes);
const router = createRouter({
	history: createWebHashHistory(),
	routes: routes,
	scrollBehavior(to, from, savedPosition) {
		if (savedPosition) {
			return savedPosition;
		} else {
			return { top: 0 };
		}
	},
	//判断是否已加载过动态/静态路由
	addDynamicRoute: false,
});

//设置标题
document.title = config.APP_NAME;

// router.beforeEach((to, from) => {
// 	console.log("router.beforeEach from -》 to", from, to);
// });

router.beforeEach(async (to, from, next) => {
	console.log("router.beforeEach -- from, to 1", from, to);
	NProgress.start();
	//动态标题
	document.title = to.meta.title
		? `${to.meta.title} - ${config.APP_NAME}`
		: `${config.APP_NAME}`;

	let token = store.getters["user/token"];

	if (to.path === "/login") {
		//TODO 删除路由(替换当前layout路由)
		// router.addRoute(routes[0]);
		alert(1);
		await store.dispatch("user/loginOut");
		next();
		return false;
	}

	if (!token && to.path !== "/login") {
		router.replace("/login");
		return false;
	}

	//整页路由处理
	if (to.meta.fullpage) {
		to.matched = [to.matched[to.matched.length - 1]];
	}
	//加载动态/静态路由
	//TODO 获取路由  UP

	if (token && !router.addDynamicRoute) {
		await addDynamicMenuRoutes(router);
		router.addDynamicRoute = true;
		// next({ ...to, replace: true });
		next(to.path);
		return false;
	}
	beforeEach(to, from);
	console.log("router.beforeEach -- from, to 2", from, to);
	next();
});

router.afterEach((to, from) => {
	afterEach(to, from);
	NProgress.done();
});

router.onError((error) => {
	NProgress.done();
	ElNotification.error({
		title: "路由错误",
		message: error.message,
	});
});
export default router;
